package com.pan.test.udp.example02;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ReceiverB {

    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(11452);
        byte[] buf = new byte[1024];
        DatagramPacket receiveDatagram = new DatagramPacket(buf,0,1024);
        datagramSocket.receive(receiveDatagram);

        byte[] receiveData = receiveDatagram.getData();
        int len  = receiveDatagram.getLength();
        String question = new String(receiveData,0,len);
        String answer = question.equals("四大名著有哪些？")?"《西游记》《红楼梦》《三国演义》《水浒传》":"我不了解";
        byte[] answerArr = answer.getBytes();
        int answerLen = answerArr.length;
        InetAddress answerAddress = receiveDatagram.getAddress();
        int answerPort = receiveDatagram.getPort();
        DatagramPacket answerPacket = new DatagramPacket(answerArr,0,answerLen,answerAddress,answerPort);
        datagramSocket.send(answerPacket);


        datagramSocket.close();

    }
}
